#include "serial_port.h"
#include "serv_datapack.h"
#include <QDebug> 

static uint8_t RecvBuff[2048];
static CBuff RecvCbuffer;

SerialPort::SerialPort(QObject *parent) : QSerialPort(parent) {
    connect(this, &QSerialPort::readyRead, this, &SerialPort::onReadyRead);
}

SerialPort::~SerialPort() {
    if (isOpen()) {
        close();
    }
}

bool SerialPort::open(const QString &portName, int baudrate) {
    setPortName(portName);
    setBaudRate(baudrate);
    setDataBits(QSerialPort::Data8);
    setParity(QSerialPort::NoParity);
    setStopBits(QSerialPort::OneStop);
    setFlowControl(QSerialPort::NoFlowControl);
    CBuff_Init(&RecvCbuffer,RecvBuff,2048);
    if (!QSerialPort::open(QIODevice::ReadWrite)) {
        return false;
    }

    return true;
}

void SerialPort::close() {
    QSerialPort::close();
}

void SerialPort::onReadyRead() {
    QByteArray data = readAll();
    //qDebug() << "Received data (Hex):" << data.toHex(' ').toUpper();
    if (!data.isEmpty()) {
        for (int i = 0; i < data.size(); ++i) {
            uint8_t byte = static_cast<uint8_t>(data.at(i));  
            CBuff_Write(&RecvCbuffer,&byte,1);
        }
    }
}

void SerialPort::HandleData(){
    static uint8_t Data[128];
    
    if (Serv_Com_UnpackFSM(&RecvCbuffer, Data) == 1) {
        QByteArray byteArray(reinterpret_cast<const char*>(Data), 128);
        qDebug() << "Received Data (Hex):" << byteArray.toHex(' ').toUpper();
    }
}